﻿var RATE = Number($.cookie("ParcelRate"));
var scrollToph;
var app_url=location.origin;
(function () {
    var cart = {
        init: function () {
            
            var num = 0;//选中的行数
            var rmb = 0;//每卡
            var total = 0;//总价
            this.loadCart();
            this.bindEvents();          
        },
        bindEvents: function () {
            var self = this;
            //导航栏的选中
             $('.wrapper').navbarscroll();
            $("#categories li").eq(2).addClass("cur").siblings().removeClass("cur");
             //跳转页面
             $("#categories a").on("click",function(){
            	var link_url=$(this).attr("data-href");
//          	if(APP){
//          		var appJson={};
//         			appJson.title=$(this).attr("data-title");
//         			appJson.url=app_url+link_url;	
//         			YiYi_APP.showNewPage(JSON.stringify(appJson));
//          	}else{
            		location.href = link_url;
            	//}
            });
            //点击关闭钻石详情
            $(".close-detail-btn").on("click", function (ev) {
                self.closeDatail($(this));
            });
            //移除购物车
            $(".remove-cart-btn").on("click", function (ev) {
            	var catrId = $("#cart .check_list_box span.selected").attr("lang");
            	if($("#cart .check_list_box span").is(".selected")){
            		myApp.confirm(_('确定移除购物车吗？'),'',function(){
            		 	self.removeCart(catrId);
            		});
            	}else{
            		myApp.alert(_("请选择!"));
            	}
            });
             //随便逛逛
           $("#go_shop").on("click",function(){
           		var link_url="/Customer/WhiteParcels?team=0";
           		if(APP){
            		appJson.function_menu="goods_search";
           			appJson.goods_type="2";
           			appJson.title="统包库存";
           			YiYi_APP.showExistingPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
           });

            //点击证书号
            $(".cert-href").on("click", function (ev) {
                self.showCert($(this));
            });
            //关闭证书
            $(".close-cert-box-btn").on("click", function (ev) {
                $(".cert-bg-box").hide();
            });
            //点击看详情
			$("#cart").on("click",".product-href", function (ev) {
            	var _id =  $(this).attr("lang");
            	var link_url="/Customer/ParcelDetails/?ID="+_id+"&team=0"
            	if(APP){
            		var appJson={};
           			appJson.title=_("统包详情");
           			appJson.url=app_url+link_url;	
           			YiYi_APP.showNewPage(JSON.stringify(appJson));
            	}else{
            		location.href = link_url;
            	}
				
           });
           //点击全选
			$("#checkbox_check_all").on("click",function(){
				$(this).toggleClass("selected")
				if($(this).hasClass("selected")){
					$(".check_list_box").children("span").addClass("selected");
					$(".check_list_box span.selected").each(function (i, item) {
						var pre = parseFloat($(item).closest("figure").find(".first").text());//当前点击行的每卡
    					var totalprice = parseFloat($(item).closest("figure").find(".totalprice").text());
    					var preRMB = parseFloat($(item).closest("figure").find(".firstRMB").text());//当前点击行的每卡
    					var totalpriceRMB = parseFloat($(item).closest("figure").find(".totalpriceRMB").text());
						self.countCheck(1,pre,totalprice,preRMB,totalpriceRMB);
					});		
				}else{
					$(".check_list_box").children("span").removeClass("selected");
					self.countCheck(0,0,0,0,0);//取消
				}
			});
			//列表的勾选框
			$("#cart").on("click",".check_list_box",function(){
				$(this).children("span").toggleClass("selected");
				var pre = parseFloat($(this).closest("figure").find(".first").text());//当前点击行的每卡
				var totalprice = parseFloat($(this).closest("figure").find(".totalprice").text());
				var preRMB = parseFloat($(this).closest("figure").find(".firstRMB").text());//当前点击行的每卡
				var totalpriceRMB = parseFloat($(this).closest("figure").find(".totalpriceRMB").text());
				//判断是否全选
				var length=$("#cart .check_list_box span.checkbox").length;
				var checkLength=$("#cart .check_list_box span.selected").length;
				if(length==checkLength){
					$("#checkbox_check_all").addClass("selected");
				}else{
					$("#checkbox_check_all").removeClass("selected");
				}				
				if($(this).children("span").hasClass("selected")){
					self.countCheck(1,pre,totalprice,preRMB,totalpriceRMB);//选中
				}else{
					self.countCheck(2,pre,totalprice,preRMB,totalpriceRMB);//取消
				}
				
			});
           
			//立即购买
			$("#add_to_order").on("click",function(){
				var cartlistCb = $("#cart .check_list_box span.selected");//tbody中checked的
                if (cartlistCb.length == 0) {
                	myApp.alert(_("请选择!"));
                } else {
                	var orderJson={};
                	orderJson.orderID = [];
                	orderJson.type="parcels";
                	orderJson.form="cart";
		            for (var i = 0; i < cartlistCb.length; i++) {
		               orderJson.orderID.push(cartlistCb[i].lang);
		            }		           
		            if(APP){
		            	var appJson={};
		            	appJson.title=_("确认下单");
		            	appJson.url=app_url+"/Customer/SubmitDiaOrder?type=2&cart=2";
		            	appJson.content=JSON.stringify(orderJson);
		            	YiYi_APP.submitOrder(JSON.stringify(appJson))
		            }else{
		            	var action="/Customer/SubmitDiaOrder?type=2&cart=2";
					  	form = $("<form method='post' id='params_form' action='"+action+"'>"+
					   	"<input type='text' value='"+JSON.stringify(orderJson)+"' name='params'></form>")
						$("#form_box").html(form);
						$("#params_form").submit();
		            }
                }
			});
        },


        //绑定数据
        bindingCart: function (result) {
            var _result = eval('(' + result + ')');//eval()解析单个json对象
            if (_result.msgcode == false || _result["msginfo"].rows.length==0) {//获取购物车失败
                $(".null-cart-tip").show();//显示空购物车提示
                $("#cart").hide();//隐藏购物车列表，主要是隐藏列表的边框线

            } else {  //获取购物车成功
                $("#cart").show();//显示购物车内容
                _result = _result["msginfo"].rows;//object;//object
                 $("#totalCart").html(_result.length);
                var figures = "";//多行数据
                for (var i = 0; i < _result.length ; i++) {//_result.length
                    var figcaption = "";//多列
                    var figure = "";//单行
                    //购物车权限start
                    var shapeCartPower=''; //形状
                        shapeCartPower="<b class='shape'>" + getBicon(GetText("parcels",_result[i].Category,_result[i].Shape,"Shape")) + "</b>"
                    var colorCartPower=''; //颜色
                        colorCartPower="<b class='color'>" + GetText("parcels",_result[i].Category,_result[i].Color,"Color")+ "</b>"
                    var clarityCartPower=''; //净度
                        clarityCartPower="<b class='clarity'>" + _result[i].Clarity +"</b>"
                    var weightCartPower=''; //总重
                        weightCartPower="<b class='weight'>" + _result[i].Weight + "</b>"
                    var placeCartPower=''; //所在地
                    if(place_td_new==true){
                        placeCartPower="<b class='place'>" + GetText("parcels",_result[i].Category,_result[i].Place,"Place") + "</b>"
                    }

                    var priceCartPower=''; //美元
                    if(price_td_new==true){
                        priceCartPower="<div class='product-price CurrentUSD'>"+
                            "<span>"+_("每卡")+"$：<b class='first'>" + formatUSDPrice(_result[i].Price) + "</b></span>" +
                            "<span>"+_("总价")+"$：<b class='totalprice'>" + formatUSDPrice(_result[i].Price * _result[i].InventoryCount) + "</b></span>"+
                            "</div>"
                    }
                    var priceRmbCartPower=''; //人民币
                    if(RMBPrice_td_new==true){
                        priceRmbCartPower="<div class='product-price CurrentRMB'>"+
                            "<span>"+_("每卡")+"￥：<b class='firstRMB'>" + formatRMBPrice(_result[i].Price*RATE) + "</b></span>" +
                            "<span>"+_("总价")+"￥：<b class='totalpriceRMB'>" + formatRMBPrice(_result[i].Price*RATE * _result[i].InventoryCount) + "</b></span>"+
                            "</div>"
                    }
                    //购物车权限end

                    //绑定数据
                    figcaption += "<figcaption class='product-parameter' lang='" + _result[i].ID + "'>"+
                    "<div style='float: left;height: 65px;width: 45px;margin-right: 10px;padding-top: 5px'><div class='imgList'>"+ShowImgOne(_result[i])+"</div></div>"+
                    	"<div style='display:inline-block;width:80%'><h3 id='h3_l'><b class='list-num' style='display:none'>" + (i + 1) + "</b>" +shapeCartPower+
                    		"<b class='size'>" + _result[i].Size + "</b>"+colorCartPower +clarityCartPower+weightCartPower+placeCartPower+
                    	"</h3></div>" + priceCartPower+priceRmbCartPower+
                   		"</div></figcaption>";
                    figure += "<figure class='product-list' data-time='" + DateTimeFormat(_result[i].UpdateTime) + "'>" +
				       "<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + _result[i].CartID + "'></span></div>"+
//                      "<div class='checkbox-cart'><input type='checkbox' lang='" + _result[i].ID + "' class='checkbox-cart' name='checkbox-cart'/></div>" +
                        "<a href='javacript:void(0)' class='product-href' lang='" + _result[i].ID + "' data-sn='" + _result[i].OriginSN + "'>" + figcaption + "</a></figure>";
                    figures += figure;//将单行加到多行
                }

                $("#cart").html(figures);//加入到id为inventory的figures中
                currentShow();  //币种设置

            }

        },

        //加载购物车
        loadCart: function () {
            var self = this;
            myApp.showIndicator();//显示加载中
            var result = {};
            result.CustomerID = CustomerID;//客户ID
            result.PageSize = 1;
            result.PageIndex = 1;
            result.type = 2;
            $.ajax({
                url: "/Customer/GetCartInfos",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    self.bindingCart(result);//绑定购物车
                    self.clearTotal();//清空选中统计
                    myApp.hideIndicator();//隐藏加载中

                }
            });
        },

        //移除购物车
        removeCart: function () {
            var self = this;
            //获取ID值
            var result = {};
            result.CustomerID = CustomerID;//客户ID
            var cartlistCb = $("#cart .check_list_box span.selected");//获取选中的行
            var _IDs = "";
            for (var i = 0; i < cartlistCb.length; i++) {
                if (i == 0)
                    _IDs += cartlistCb[i].lang;
                else
                    _IDs += "," + cartlistCb[i].lang;
            }
            result.GoodsType=2;
            result.CartIDs = _IDs;
            $.ajax({
                url: "/Customer/RemoveCart",//提交地址
                type: "POST",//提交方式
                data: JSON.stringify(result),
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var _result = eval('(' + result + ')');//eval()解析单个json对象

                    if (_result['msgcode'] == false) {
                        toast(_result['msginfo']);
                    } else {
                        $("#removeTip").hide();
                        toast(_result['msginfo']);
                        setTimeout(function () {
                            $(".detail-box-bg").hide();
                        }, 1000);
                        self.loadCart();
                        //启用滚动条
                        $("body").css({
                            "overflow": "auto",
                            'position': 'static',
                            'top': 'auto'
                        });
                        $("body").scrollTop(scrollToph);

                    }
                }
            });
        },

      
		countCheck:function(type,pre,totalPrice,preRMB,totalPriceRMB){			
			var price=parseFloat($("#check-total-priceUSD").text());
			var pre_price=parseFloat($("#check-m-usd").text());
			var priceRMB=parseFloat($("#check-total-price").text());
			var pre_priceRMB=parseFloat($("#check-m-rmb").text());
			var _num = $(".check_list_box span.selected").length;;	
			if(type==1){//加
				price+=totalPrice
				pre_price+=pre
				priceRMB+=totalPriceRMB
				pre_priceRMB+=preRMB
			}
			if(type==2){//减
				price-=totalPrice
				pre_price-=pre
				priceRMB-=totalPriceRMB
				pre_priceRMB-=preRMB
			}
			if(type==0){
				_num=0;
				price=0;
				pre_price=0;
				priceRMB=0;
				pre_priceRMB=0;
			}
			$("#check-num").text(_num);
			$("#check-m-rmb").text(formatRMBPrice(pre_priceRMB));
			$("#check-total-price").text(formatUSDPrice(priceRMB));
			$("#check-m-usd").text(formatUSDPrice(pre_price));
			$("#check-total-priceUSD").text(formatRMBPrice(price)); 
		},
        //清空统计栏
        clearTotal: function () {
            $("#check-num").html(0);
            $("#check-m-rmb").html(0);
            $("#check-total-price").html(0);
             $("#check-m-usd").html(0);
            $("#check-total-priceUSD").html(0);
        },
    };
    cart.init();
})();
//勾选统计
function CurrSelectedEvent(me) {
    var self = $(me);
    var check = self.is(':checked');//当前点击的是否选中
    num = parseInt($("#check-num").html());//获取统计栏的选中的行数
    rmb = parseInt($("#check-m-rmb").html());//获取统计栏选中的每卡
    total = parseInt($("#check-total-price").html());//获取统计栏中的总价
    var r = parseInt(self.parent().parent().find(".first").html());//当前点击行的每卡
    var t = parseInt(self.parent().parent().find(".totalprice").html());//当前点击行的总价
    if (check) {//选中
        num += 1;//行数加1
        rmb += r;//统计栏中的每卡+当前点击的每卡
        total += t;//总价+当前选中的总价
    } else {//取消选中
        num -= 1;//行数减1
        rmb -= r;//统计栏中的每卡-当前点击的每卡
        total -= t;//总价-当前点击的总价
    }
    $("#check-num").html(num);//赋值行数
    $("#check-m-rmb").html(rmb);//赋值每卡
    $("#check-total-price").html(total);//赋值总价
}

